package net.TCPTwoWayChat;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TwoWayClient {

    public static void main(String[] args) throws IOException {

        Socket clientSocket = new Socket("localhost", 8888);
        System.out.println("客户端与服务端连接成功");

        //创建一个从客户端的一个输入流
        BufferedReader fromServerStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        //创建一个向客户端写出的输出流
        PrintWriter toServerStream = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));


        //使用匿名内部类的形式创建一个从服务端向客户端写数据的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                Scanner scan = new Scanner(System.in);
                while(true){
                    String message = scan.nextLine();
                    toServerStream.println(message);
                    toServerStream.flush();
                }
            }
        }).start();

        //使用匿名内部类的形式创建一个从客户端读数据的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String line;
                    while((line=fromServerStream.readLine())!=null){
                        System.out.println("服务端说:"+line);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

}
